import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/scene_model.dart';

class SceneProvider with ChangeNotifier {
  late SharedPreferences _prefs;
  List<LightScene> _scenes = [];
  LightScene? _currentScene;
  
  // Getter
  List<LightScene> get scenes => _scenes;
  LightScene? get currentScene => _currentScene;
  
  // 预设场景
  final List<LightScene> _defaultScenes = [
    LightScene(
      id: 'indoor',
      name: '室内补光',
      description: '适合室内拍摄的均衡光线',
      iconName: 'home',
      brightness: 0.7,
      colorTemperature: 0.5,
    ),
    LightScene(
      id: 'outdoor',
      name: '户外逆光',
      description: '补充逆光环境下的前景光线',
      iconName: 'wb_sunny',
      brightness: 1.0,
      colorTemperature: 0.6,
    ),
    LightScene(
      id: 'night',
      name: '夜间补光',
      description: '柔和的夜间补光效果',
      iconName: 'nightlight',
      brightness: 0.4,
      colorTemperature: 0.3,
    ),
    LightScene(
      id: 'live',
      name: '直播补光',
      description: '适合视频直播的明亮光线',
      iconName: 'videocam',
      brightness: 0.8,
      colorTemperature: 0.7,
    ),
  ];

  // 初始化
  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
    await _loadScenes();
  }

  // 加载场景
  Future<void> _loadScenes() async {
    final customScenesJson = _prefs.getStringList('custom_scenes') ?? [];
    final customScenes = customScenesJson
        .map((json) => LightScene.fromJson(jsonDecode(json)))
        .toList();
    
    _scenes = [..._defaultScenes, ...customScenes];
    
    // 加载当前场景
    final currentSceneJson = _prefs.getString('current_scene');
    if (currentSceneJson != null) {
      _currentScene = LightScene.fromJson(jsonDecode(currentSceneJson));
    }
    
    notifyListeners();
  }

  // 保存自定义场景
  Future<void> _saveCustomScenes() async {
    final customScenes = _scenes
        .where((scene) => scene.isCustom)
        .map((scene) => jsonEncode(scene.toJson()))
        .toList();
    
    await _prefs.setStringList('custom_scenes', customScenes);
  }

  // 添加自定义场景
  Future<void> addCustomScene(LightScene scene) async {
    final newScene = scene.copyWith(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      isCustom: true,
    );
    
    _scenes.add(newScene);
    await _saveCustomScenes();
    notifyListeners();
  }

  // 删除场景
  Future<void> deleteScene(String sceneId) async {
    _scenes.removeWhere((scene) => scene.id == sceneId && scene.isCustom);
    await _saveCustomScenes();
    notifyListeners();
  }

  // 选择场景
  Future<void> selectScene(String sceneId) async {
    final scene = _scenes.firstWhere((scene) => scene.id == sceneId);
    _currentScene = scene;
    await _prefs.setString('current_scene', jsonEncode(scene.toJson()));
    notifyListeners();
  }

  // 清除当前场景
  Future<void> clearCurrentScene() async {
    _currentScene = null;
    await _prefs.remove('current_scene');
    notifyListeners();
  }
}
